# Create your views here.
from inc import * 
# NOTICE: This is the top level module, do not import this file.

def ShortCut(request,name):
    service_t = loader.get_template('shortcut.html')
    try:
      data = ServiceCore.objects.get(name=name)
      c = Context({'REQUEST':request.REQUEST,'DATA':data})
      return HttpResponse(service_t.render(c),mimetype = "text/xml")
    except ServiceCore.DoesNotExist:
      return HttpResponse("Error")

def Admin(request):
# The get service will always provides all the services
    services = ServiceCore.objects.all()
    data_t = loader.get_template('admin.html')
    c = Context({'DATA':services,'SESSION':request.session})
    response = HttpResponse(data_t.render(c),mimetype = "text/html")
    response['Cache-Control'] = 'no-cache'
    return response

def Search(request):
    filter_str = request.REQUEST['filter']
    filter_dict = json.loads(filter_str)
    services = ServiceCore.objects.all();
    if(filter_dict.has_key('NATIONA') and filter_dict['NATION'] != 'MIXED'):
      services = services.filter(nation = filter_dict['NATION'])
    if(filter_dict.has_key('PRICE') 
      and filter_dict['PRICE'].has_key('MIN') 
      and filter_dict['PRICE']['MIN'] != 'UNLIMITED'):
      services = services.filter(pricelow__lte = (int (filter_dict['PRICE']['MIN'])))
    if(filter_dict.has_key('PRICE') 
      and filter_dict['PRICE'].has_key('MAX') 
      and filter_dict['PRICE']['MAX'] != 'UNLIMITED'):
      services = services.filter(pricelow__lte = (int (filter_dict['PRICE']['MAX'])))
    results = []
    distances = {}
    if(filter_dict.has_key('LOCATION') and filter_dict.has_key('RADIUS')):
      llbase = {'lat':float(filter_dict['LOCATION']['x']),'long':float(filter_dict['LOCATION']['y'])}
      if llbase['lat'] and llbase['long']:
        for service in services:
          llinc = {'lat':float(service.latitude)/1000000,'long':float(service.longitude)/1000000}
          dis = ComputeDistance(llbase,llinc)
          if(dis < int(filter_dict['RADIUS'])):
            distances[service.name] = dis
            results.append(service)
      else:
        results = services
    data_t = loader.get_template('admin.html')
    loc = filter_dict['LOCATION']
    c = Context({'DATA':results,'SESSION':request.session,"LOC":loc,"DIS":distances})
    response = HttpResponse(data_t.render(c),mimetype = "text/html")
    response['Cache-Control'] = 'no-cache'
    return response

def Service(request,name):
    comp_dict = {'post_list':'comp/_post_list.html',
                 'icon':'comp/_icon.html',
                 'gallery':'comp/_gallery.html',
                 'girls':'comp/_girls.html',
                 'timetable':'comp/_timetable.html',
                 'roster':'comp/_roster.html'}
    aut = HasAuthority(request,name)
    service_t = None
    today = date.today()
    now = datetime.now()
    tstamp = now.strftime("%Y-%m-%d-%H-%M-%S")
    dic = {'CSS_ROOT':'default'}
    if (request.REQUEST.has_key('comp') and comp_dict.has_key(request.REQUEST['comp'])):
      comp = request.REQUEST['comp']
      service_t = loader.get_template(comp_dict[comp])
      if (request.REQUEST.has_key('day')):
        dic['WEEK_DAY'] = CONFIG.WEEK_DAY_NAME[int (request.REQUEST['day'])]
      else:
        dic['WEEK_DAY'] = CONFIG.WEEK_DAY_NAME[today.weekday()]
    else:
      service_t = loader.get_template('service.html')
      dic['ROOT'] = 'ROOT'
      dic['WEEK_DAY'] = CONFIG.WEEK_DAY_NAME[today.weekday()]
    try:
      data = ServiceCore.objects.get(name=name)
      dic['SERVICE'] = data
      if (aut['r'] == True):
        dic['HAS_AUTHORITY'] = True
        dic['TIME_STAMP'] = tstamp
      gnode = etree.parse(CONFIG.SERVICES_PATH + name+'/config.xml')
      gallery = Gallery.InitGalleryConfig(gnode.getroot())
      girls = Girls.InitGirlsConfig(gnode.getroot())
      timetable = TimeTable.InitTimeTableConfig(gnode.getroot())
      post = Post.InitPostConfig(gnode.getroot())
      layout = Layout.InitLayoutConfig(gnode.getroot())
      girls_info = girls.BasicInfo()
      gallery_info = gallery.BasicInfo()
      timetable_info = timetable.BasicInfo()
      layout_info = layout.GetLayout()
      post_info = post.BasicInfo()
      dic['GALLERY_INFO'] = gallery_info
      dic['GIRLS_INFO'] = girls_info
      dic['ROSTER_INFO'] = timetable_info[dic['WEEK_DAY']]['roster']
      dic['TIMETABLE_INFO'] = timetable_info
      dic['POST_INFO'] = post_info
      dic['LAYOUT_INFO'] = layout_info
      c = Context(dic)
      return HttpResponse(service_t.render(c),mimetype = "text/html")
    except ServiceCore.DoesNotExist:
      return HttpResponse("Service Does Not Exist")
